<template>
  <Modal
      :show="show"
      title="添加"
      @ok="handleOk"
      @cancel="handleCancel"
  >
    <ModalForm ref="form"></ModalForm>
  </Modal>
</template>

<script lang="ts">
export default {
  name: "RoleModal"
}
</script>

<script setup lang="ts">
import {nextTick, onMounted, ref} from "vue"
import Modal from '@/components/Modal.vue'
import {RoleListType, RoleSaveType} from '@/view/system/role/RoleType'
import ModalForm from '@/components/ModalForm.vue'
import {ModalFormInitType} from '@/type/ModalFormType'
import {ums_role_save, ums_role_update} from '@/api/ums'
import useMsg from '@/hooks/useMsg'

const {success, error} = useMsg()

const emit = defineEmits<{
  (e: 'list'): void
}>()

const roleId = ref<string>()

const form = ref<{
  init: (data: ModalFormInitType[]) => void
  validate: () => Promise<RoleSaveType>
}>()

const type = ref<0|1>(0)

const show = ref<boolean>(false)

const title = ref<string>("添加")

const handleOk = () => {
  form.value?.validate().then(data => {
    if (type.value === 0) {
      ums_role_save(data).then(res => {
        if (res.code === 200) {
          success(res.message)
          emit("list")
          show.value = false
        }else {
          error(res.message)
        }
      })
    }
    if (type.value === 1) {
      ums_role_update({
        ...data,
        roleId: roleId.value!
      }).then(res => {
        if (res.code === 200) {
          success(res.message)
          show.value = false
          emit("list")
        }else {
          error(res.message)
        }
      })
    }
  })
}

const handleCancel = () => {
  show.value = false
}

function init (data?: RoleListType) {
  if (data) {
    type.value = 1
    title.value = '编辑'
    roleId.value = data.roleId
  }else {
    type.value = 0
    title.value = '添加'
  }
  show.value = true
  nextTick(() => {
    form.value?.init([
      {
        label: "角色名称",
        type: "input",
        key: "roleName",
        value: data?.roleName,
        rules:{
          required: true,
          trigger: "change",
          message: "请输入角色名称"
        }
      },
      {
        label: "排序",
        type: "number",
        key: "role_order",
        value: data?.role_order,
        rules:{
          type: "number",
          required: true,
          trigger: "change",
          message: "请输入排序数字"
        }
      },
      {
        label: "状态",
        type: "radio",
        key: "status",
        value: data?.status,
        rules:{
          type: "number",
          required: true,
          trigger: "change",
          message: "请选择角色状态"
        },
        options: [
          {
            label: "禁用",
            value: 0
          },
          {
            label: "启用",
            value: 1
          }
        ]
      }
    ])
  })
}


defineExpose({
  init
})

onMounted( () => {
} )
</script>

<style scoped lang="scss">

</style>
